import { ref, onMounted, onUnmounted, watchEffect } from 'vue'
import * as ol from 'ol'
import * as olProj from 'ol/proj'
import { unByKey } from 'ol/Observable'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'
import { Draw } from 'ol/interaction'
import { LineString, Polygon } from 'ol/geom'
import { getArea, getLength } from 'ol/sphere'
import { getCenter } from 'ol/extent'
import Overlay from 'ol/Overlay'
import { ElMessage } from 'element-plus'

/**
 * 地图测量工具钩子函数
 * @returns {Object} 测量工具相关方法和状态
 */
export function useMeasure() {
  // 全局样式处理
  const addGlobalStyle = () => {
    if (document.getElementById('measure-tools-style')) return;
    
    const style = document.createElement('style');
    style.id = 'measure-tools-style';
    style.innerHTML = `
      .ol-overlay-container {
        pointer-events: none;
      }
      .ol-overlay-container * {
        pointer-events: none;
      }
      .measure-tools {
        pointer-events: auto !important;
        z-index: 10000 !important;
      }
      .measure-tools button {
        pointer-events: auto !important;
        position: relative;
        z-index: 10001 !important;
      }
      #stopMeasureBtn {
        cursor: pointer !important;
        pointer-events: auto !important;
      }
      .ol-interaction {
        pointer-events: auto !important;
      }
      .ol-draw {
        pointer-events: auto !important;
      }
      .ol-draw * {
        pointer-events: auto !important;
      }
      .ol-draw-handle {
        pointer-events: auto !important;
      }
      .ol-draw-handle * {
        pointer-events: auto !important;
      }
      .ol-tooltip {
        pointer-events: none !important;
      }
      .ol-tooltip-measure {
        pointer-events: none !important;
      }
      .ol-tooltip-static {
        pointer-events: none !important;
      }
    `;
    document.head.appendChild(style);
  };

  // 在组件挂载时添加全局样式
  onMounted(() => {
    addGlobalStyle();
  });

  const map = ref(null);
  const draw = ref(null); // 当前绘制对象
  const source = ref(null); // 矢量图层源
  const vector = ref(null); // 矢量图层
  const helpTooltipElement = ref(null);
  const helpTooltip = ref(null);
  const measureTooltipElement = ref(null);
  const measureTooltip = ref(null);
  const continuePolygonMsg = '点击继续绘制多边形';
  const continueLineMsg = '点击继续绘制线段';
  const measureTooltips = ref([]);
  const measureTooltipElements = ref([]); // 添加提示元素引用数组
  const isMeasuring = ref(false);
  const measureType = ref('');
  const drawStartListener = ref(null);
  const drawEndListener = ref(null);
  const pointerMoveListener = ref(null);
  const initialized = ref(false);
  const hasError = ref(false);
  const errorMsg = ref('');

  // 初始化地图
  const initMap = (mapInstance) => {
    if (!mapInstance) {
      console.error('初始化测量工具失败: 地图实例为空');
      hasError.value = true;
      errorMsg.value = '地图实例为空';
      return false;
    }
    
    try {
      map.value = mapInstance;
      console.log('地图实例已设置');
      
      // 检查是否处于3D模式
      const is3DMode = mapInstance.getView().getProjection().getCode() === 'EPSG:4326';
      console.log('当前地图模式:', is3DMode ? '3D模式' : '2D模式');
      
      // 统一使用相同的样式，无论是2D还是3D模式
      const lineWidth = 1;
      const circleRadius = 3;
      
      // 创建矢量图层
      source.value = new VectorSource();
      vector.value = new VectorLayer({
        source: source.value,
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: lineWidth
          }),
          image: new CircleStyle({
            radius: circleRadius,
            fill: new Fill({
              color: '#ffcc33'
            })
          })
        })
      });
      
      map.value.addLayer(vector.value);
      console.log('测量图层添加成功');
      initialized.value = true;
      
      // 清除错误状态
      hasError.value = false;
      errorMsg.value = '';
      
      // 确保测量工具在3D模式下正常工作
      ensure3DInteractionWorks();
      
      return true;
    } catch (error) {
      console.error('初始化测量工具失败:', error);
      hasError.value = true;
      errorMsg.value = '初始化测量工具失败: ' + error.message;
      return false;
    }
  };

  const isReady = () => {
    const ready = !!map.value && initialized.value;
    console.log('测量工具就绪状态检查:', ready ? '已就绪' : '未就绪');
    return ready;
  };

  // 获取输出格式
  const formatLength = (line) => {
    const length = getLength(line);
    let output;
    if (length > 100) {
      output = Math.round((length / 1000) * 100) / 100 + ' km';
    } else {
      output = Math.round(length * 100) / 100 + ' m';
    }
    return output;
  };

  const formatArea = (polygon) => {
    const area = getArea(polygon);
    let output;
    if (area > 10000) {
      output = Math.round((area / 1000000) * 100) / 100 + ' km²';
    } else {
      output = Math.round(area * 100) / 100 + ' m²';
    }
    return output;
  };

  // 创建提示框
  const createHelpTooltip = () => {
    if (helpTooltipElement.value) {
      helpTooltipElement.value.parentNode.removeChild(helpTooltipElement.value);
    }
    helpTooltipElement.value = document.createElement('div');
    helpTooltipElement.value.className = 'ol-tooltip hidden';
    helpTooltipElement.value.style.pointerEvents = 'none';
    
    helpTooltip.value = new Overlay({
      element: helpTooltipElement.value,
      offset: [15, 0],
      positioning: 'center-left',
      stopEvent: false
    });
    map.value.addOverlay(helpTooltip.value);
  };

  // 创建测量提示框
  const createMeasureTooltip = () => {
    if (measureTooltipElement.value) {
      measureTooltipElement.value.parentNode.removeChild(measureTooltipElement.value);
    }
    measureTooltipElement.value = document.createElement('div');
    measureTooltipElement.value.className = 'ol-tooltip ol-tooltip-measure';
    measureTooltipElement.value.style.pointerEvents = 'none';
    
    measureTooltip.value = new Overlay({
      element: measureTooltipElement.value,
      offset: [0, -15],
      positioning: 'bottom-center',
      stopEvent: false
    });
    map.value.addOverlay(measureTooltip.value);
    measureTooltips.value.push(measureTooltip.value);
    measureTooltipElements.value.push(measureTooltipElement.value); // 添加到元素数组
  };

  // 添加交互式绘图
  const addInteraction = (type) => {
    console.log(`添加绘图交互 - 类型: ${type}, 地图状态:`, map.value ? '可用' : '不可用');
    const activeMeasureType = type === 'area' ? 'Polygon' : 'LineString';
    
    // 确保先移除现有的draw实例
    if (draw.value) {
      try {
        map.value.removeInteraction(draw.value);
        console.log('已移除现有绘图交互');
      } catch (e) {
        console.error('移除现有绘图交互失败:', e);
      }
      draw.value = null;
    }
    
    // 创建新的绘图交互
    try {
      // 检查是否处于3D模式
      const is3DMode = map.value.getView().getProjection().getCode() === 'EPSG:4326';
      console.log('当前地图模式:', is3DMode ? '3D模式' : '2D模式');
      
      // 统一使用相同的线宽，无论是2D还是3D模式
      const lineWidth = 1;
      console.log('设置统一线宽:', lineWidth);
      
      draw.value = new Draw({
        source: source.value,
        type: activeMeasureType,
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.5)'
          }),
          stroke: new Stroke({
            color: '#1890ff',
            lineDash: [10, 10],
            width: lineWidth
          }),
          image: new CircleStyle({
            radius: 3,
            stroke: new Stroke({
              color: '#1890ff',
              width: lineWidth
            }),
            fill: new Fill({
              color: '#ffffff'
            })
          })
        }),
        stopClick: false, // 允许点击事件继续传播
        stopEvent: false  // 允许事件继续传播
      });
      
      // 专门处理3D模式下的事件穿透问题
      ensure3DInteractionWorks();
      
      // 添加鼠标移动事件监听
      if (pointerMoveListener.value) {
        try {
          unByKey(pointerMoveListener.value);
        } catch (e) {
          console.warn('解绑pointerMove事件失败:', e);
        }
      }
      
      // 添加鼠标移动事件监听，用于显示帮助提示
      pointerMoveListener.value = map.value.on('pointermove', (evt) => {
        if (evt.dragging) return;
        
        let helpMsg = '';
        if (type === 'area') {
          helpMsg = continuePolygonMsg;
        } else {
          helpMsg = continueLineMsg;
        }
        
        if (helpTooltipElement.value) {
          helpTooltipElement.value.innerHTML = helpMsg;
          helpTooltip.value.setPosition(evt.coordinate);
          helpTooltipElement.value.classList.remove('hidden');
        }
      });
      
      // 绘图开始事件
      if (drawStartListener.value) {
        try {
          unByKey(drawStartListener.value);
        } catch (e) {
          console.warn('解绑drawStart事件失败:', e);
        }
      }
      
      drawStartListener.value = draw.value.on('drawstart', (evt) => {
        try {
          console.log('开始测量绘制');
          isMeasuring.value = true; // 明确设置测量状态
          measureType.value = type;
          
          // 创建测量提示
          createMeasureTooltip();
          createHelpTooltip();
          
          let sketch = evt.feature;
          let geom = sketch.getGeometry();
          
          let listener;
          listener = geom.on('change', (e) => {
            try {
              let geom = e.target;
              let output;
              if (geom instanceof Polygon) {
                output = formatArea(geom);
                // 获取多边形的中心点作为提示位置
                let extent = geom.getExtent();
                let center = getCenter(extent);
                measureTooltipElement.value.innerHTML = output;
                measureTooltip.value.setPosition(center);
              } else if (geom instanceof LineString) {
                output = formatLength(geom);
                // 获取线的最后一个点作为提示位置
                let coordinates = geom.getCoordinates();
                let lastCoord = coordinates[coordinates.length - 1];
                measureTooltipElement.value.innerHTML = output;
                measureTooltip.value.setPosition(lastCoord);
              }
            } catch (err) {
              console.error('测量几何变化处理出错:', err);
            }
          });
          
        } catch (error) {
          console.error('处理测量绘制开始事件失败:', error);
        }
      });
      
      // 绘图结束事件
      if (drawEndListener.value) {
        try {
          unByKey(drawEndListener.value);
        } catch (e) {
          console.warn('解绑drawEnd事件失败:', e);
        }
      }
      
      drawEndListener.value = draw.value.on('drawend', () => {
        try {
          console.log('测量绘制结束');
          // 保存当前测量提示元素到数组中
          if (measureTooltipElement.value) {
            measureTooltipElement.value.className = 'ol-tooltip ol-tooltip-static';
            measureTooltip.value.setOffset([0, -7]);
            // 确保提示元素被正确存储
            if (!measureTooltipElements.value.includes(measureTooltipElement.value)) {
              measureTooltipElements.value.push(measureTooltipElement.value);
            }
            // 重置当前测量提示元素，以便下次测量
            measureTooltipElement.value = null;
          }
          
          // 保持测量状态为true，直到用户手动停止测量
          // 注意：这里不设置isMeasuring = false，因为用户可能会继续添加测量
        } catch (error) {
          console.error('处理测量绘制结束事件失败:', error);
        }
      });
      
      // 添加到地图
      map.value.addInteraction(draw.value);
      console.log('测量绘图交互已添加到地图');
      
      // 强制刷新地图视图，确保交互状态被正确应用
      map.value.render();
      
      // 添加一个短暂延迟，确保交互状态被正确应用
      setTimeout(() => {
        try {
          // 再次刷新地图视图
          map.value.render();
          console.log('延迟后再次刷新地图视图');
          
          // 确保绘图交互元素可点击
          const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
          drawElements.forEach(el => {
            el.style.pointerEvents = 'auto';
            el.style.zIndex = '2002';
          });
        } catch (e) {
          console.warn('延迟刷新地图视图失败:', e);
        }
      }, 100);
    } catch (error) {
      console.error('创建测量绘图交互失败:', error);
      ElMessage.error('初始化测量工具失败');
    }
  };
  
  /**
   * 确保在3D模式下交互正常工作
   */
  const ensure3DInteractionWorks = () => {
    try {
      // 检查是否处于3D模式
      const is3DMode = document.querySelector('.cesium-widget');
      if (!is3DMode) return;
      
      console.log('检测到3D模式，启用特殊处理确保测量工具可用');
      
      // 添加特殊样式，确保事件穿透和组件可见
      if (!document.getElementById('measure-3d-fix-style')) {
        const style = document.createElement('style');
        style.id = 'measure-3d-fix-style';
        style.innerHTML = `
          .ol-viewport {
            z-index: 1000 !important;
            pointer-events: auto !important;
          }
          .ol-overlay-container {
            pointer-events: none;
          }
          .ol-overlay-container.measure-tools {
            pointer-events: auto !important;
          }
          .measure-tools {
            z-index: 2000 !important;
            pointer-events: auto !important;
          }
          .measure-tools button {
            z-index: 2001 !important;
            pointer-events: auto !important;
            position: relative;
          }
          .ol-unselectable {
            pointer-events: auto !important;
          }
          .ol-interaction {
            pointer-events: auto !important;
          }
          .ol-draw {
            pointer-events: auto !important;
          }
          .ol-draw * {
            pointer-events: auto !important;
          }
          .ol-draw-handle {
            pointer-events: auto !important;
          }
          .ol-draw-handle * {
            pointer-events: auto !important;
          }
        `;
        document.head.appendChild(style);
      }
      
      // 确保测量容器可点击
      setTimeout(() => {
        const measureContainer = document.querySelector('.measure-tools');
        if (measureContainer) {
          measureContainer.style.zIndex = '2000';
          measureContainer.style.pointerEvents = 'auto';
          
          const buttons = measureContainer.querySelectorAll('button');
          buttons.forEach(btn => {
            btn.style.pointerEvents = 'auto';
            btn.style.position = 'relative';
            btn.style.zIndex = '2001';
          });
        }
        
        // 确保绘图交互元素可点击
        const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
        drawElements.forEach(el => {
          el.style.pointerEvents = 'auto';
          el.style.zIndex = '2002';
        });
      }, 500);
    } catch (error) {
      console.error('确保3D模式下测量工具可用失败:', error);
    }
  };

  // 开始测量距离
  const measureDistance = () => {
    try {
      console.log('开始测量距离...');
      if (!isReady()) {
        console.error('地图未就绪，无法测量距离');
        return false;
      }
      
      // 如果已经在测量，先停止当前测量
      if (isMeasuring.value) {
        stopMeasure();
      }
      
      // 确保地图视图已刷新
      try {
        map.value.render();
      } catch (e) {
        console.warn('刷新地图视图失败:', e);
      }
      
      // 明确设置测量状态
      isMeasuring.value = true;
      measureType.value = 'length';
      console.log('距离测量状态已设置 - 正在测量:', isMeasuring.value);
      
      // 添加绘图交互
      addInteraction('length');
      
      // 再次刷新地图视图，确保交互状态被正确应用
      setTimeout(() => {
        try {
          map.value.render();
          console.log('延迟后再次刷新地图视图');
          
          // 确保绘图交互元素可点击
          const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
          drawElements.forEach(el => {
            el.style.pointerEvents = 'auto';
            el.style.zIndex = '2002';
          });
        } catch (e) {
          console.warn('延迟刷新地图视图失败:', e);
        }
      }, 100);
      
      return true;
    } catch (error) {
      console.error('启动距离测量失败:', error);
      isMeasuring.value = false;
      measureType.value = '';
      return false;
    }
  };

  // 开始测量面积
  const measureArea = () => {
    try {
      console.log('开始测量面积...');
      if (!isReady()) {
        console.error('地图未就绪，无法测量面积');
        return false;
      }
      
      // 如果已经在测量，先停止当前测量
      if (isMeasuring.value) {
        stopMeasure();
      }
      
      // 确保地图视图已刷新
      try {
        map.value.render();
      } catch (e) {
        console.warn('刷新地图视图失败:', e);
      }
      
      // 明确设置测量状态
      isMeasuring.value = true;
      measureType.value = 'area';
      console.log('面积测量状态已设置 - 正在测量:', isMeasuring.value);
      
      // 添加绘图交互
      addInteraction('area');
      
      // 再次刷新地图视图，确保交互状态被正确应用
      setTimeout(() => {
        try {
          map.value.render();
          console.log('延迟后再次刷新地图视图');
          
          // 确保绘图交互元素可点击
          const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
          drawElements.forEach(el => {
            el.style.pointerEvents = 'auto';
            el.style.zIndex = '2002';
          });
        } catch (e) {
          console.warn('延迟刷新地图视图失败:', e);
        }
      }, 100);
      
      return true;
    } catch (error) {
      console.error('启动面积测量失败:', error);
      isMeasuring.value = false;
      measureType.value = '';
      return false;
    }
  };

  // 停止测量
  const stopMeasure = () => {
    console.log('停止测量...');
    try {
      if (!map.value) {
        console.warn('地图未初始化，无需停止测量');
        isMeasuring.value = false;
        measureType.value = '';
        return false;
      }
      
      // 1. 移除所有交互
      if (draw.value) {
        try {
          map.value.removeInteraction(draw.value);
          console.log('绘图交互已移除');
        } catch (e) {
          console.error('移除绘图交互失败:', e);
        }
        draw.value = null;
      }
      
      // 2. 移除所有事件监听
      if (drawStartListener.value) {
        try {
          unByKey(drawStartListener.value);
        } catch (e) {
          console.warn('解绑drawStart事件失败:', e);
        }
        drawStartListener.value = null;
      }
      
      if (drawEndListener.value) {
        try {
          unByKey(drawEndListener.value);
        } catch (e) {
          console.warn('解绑drawEnd事件失败:', e);
        }
        drawEndListener.value = null;
      }
      
      if (pointerMoveListener.value) {
        try {
          unByKey(pointerMoveListener.value);
        } catch (e) {
          console.warn('解绑pointerMove事件失败:', e);
        }
        pointerMoveListener.value = null;
      }
      
      // 3. 移除所有提示
      if (helpTooltip.value) {
        try {
          map.value.removeOverlay(helpTooltip.value);
        } catch (e) {
          console.warn('移除帮助提示失败:', e);
        }
        helpTooltip.value = null;
      }
      
      if (helpTooltipElement.value) {
        try {
          if (helpTooltipElement.value.parentNode) {
            helpTooltipElement.value.parentNode.removeChild(helpTooltipElement.value);
          }
        } catch (e) {
          console.warn('移除帮助提示元素失败:', e);
        }
        helpTooltipElement.value = null;
      }
      
      if (measureTooltip.value) {
        try {
          map.value.removeOverlay(measureTooltip.value);
        } catch (e) {
          console.warn('移除测量提示失败:', e);
        }
        measureTooltip.value = null;
      }
      
      if (measureTooltipElement.value) {
        try {
          if (measureTooltipElement.value.parentNode) {
            measureTooltipElement.value.parentNode.removeChild(measureTooltipElement.value);
          }
        } catch (e) {
          console.warn('移除测量提示元素失败:', e);
        }
        measureTooltipElement.value = null;
      }
      
      // 4. 重置所有状态
      isMeasuring.value = false;
      measureType.value = '';
      
      // 5. 确保3D模式下的交互也被正确清除
      ensure3DInteractionWorks();
      
      // 6. 强制刷新地图视图
      try {
        map.value.render();
        console.log('地图视图已刷新');
      } catch (e) {
        console.warn('刷新地图视图失败:', e);
      }
      
      // 7. 添加一个短暂延迟，确保所有状态都被正确应用
      setTimeout(() => {
        try {
          // 再次检查并移除任何可能残留的交互
          if (draw.value) {
            map.value.removeInteraction(draw.value);
            draw.value = null;
          }
          
          // 移除所有绘图相关的DOM元素
          const drawElements = document.querySelectorAll('.ol-draw, .ol-draw-handle');
          drawElements.forEach(el => {
            if (el && el.parentNode) {
              el.parentNode.removeChild(el);
            }
          });
          
          // 再次刷新地图视图
          map.value.render();
          console.log('延迟后再次刷新地图视图');
        } catch (e) {
          console.warn('延迟清理失败:', e);
        }
      }, 100);
      
      console.log('测量已完全停止，状态已重置');
      return true;
    } catch (error) {
      console.error('停止测量过程中发生错误:', error);
      // 确保状态被重置，即使出错
      isMeasuring.value = false;
      measureType.value = '';
      return false;
    }
  };

  // 清除所有测量
  const clearAll = () => {
    console.log('清除所有测量...');
    try {
      // 先停止当前测量
      stopMeasure();
      
      // 清除矢量源
      if (source.value) {
        source.value.clear();
        console.log('矢量源已清空');
      }
      
      // 安全地移除所有测量提示
      if (measureTooltips.value && Array.isArray(measureTooltips.value)) {
        measureTooltips.value.forEach(tooltip => {
          if (map.value && tooltip) {
            try {
              map.value.removeOverlay(tooltip);
            } catch (e) {
              console.warn('移除测量提示时出错:', e);
            }
          }
        });
        measureTooltips.value = [];
        console.log('所有测量提示已清除');
      }
      
      // 安全地移除所有提示元素
      if (measureTooltipElements.value && Array.isArray(measureTooltipElements.value)) {
        measureTooltipElements.value.forEach(element => {
          if (element && element.parentNode) {
            try {
              element.parentNode.removeChild(element);
            } catch (e) {
              console.warn('移除测量提示元素时出错:', e);
            }
          }
        });
        measureTooltipElements.value = [];
        console.log('所有测量提示元素已清除');
      }
      
      // 确保状态被重置
      isMeasuring.value = false;
      measureType.value = '';
      
      // 清除错误状态
      hasError.value = false;
      errorMsg.value = '';
      
      // 移除所有交互
      if (map.value) {
        if (draw.value) {
          map.value.removeInteraction(draw.value);
          draw.value = null;
        }
        
        // 移除所有事件监听
        if (drawStartListener.value) {
          unByKey(drawStartListener.value);
          drawStartListener.value = null;
        }
        
        if (drawEndListener.value) {
          unByKey(drawEndListener.value);
          drawEndListener.value = null;
        }
        
        if (pointerMoveListener.value) {
          unByKey(pointerMoveListener.value);
          pointerMoveListener.value = null;
        }
      }
      
      console.log('所有测量已成功清除');
      return true;
    } catch (error) {
      console.error('清除测量时发生错误:', error);
      hasError.value = true;
      errorMsg.value = '清除测量失败: ' + error.message;
      
      // 确保状态被重置，即使出错
      isMeasuring.value = false;
      measureType.value = '';
      
      return false;
    }
  };

  // 组件卸载时清理
  onUnmounted(() => {
    console.log('测量工具卸载中...');
    clearAll();
    
    // 移除全局样式
    const styleElement = document.getElementById('measure-tools-style');
    if (styleElement) {
      styleElement.parentNode.removeChild(styleElement);
      console.log('测量工具全局样式已移除');
    }
  });

  return {
    initMap,
    isReady,
    measureDistance,
    measureArea,
    stopMeasure,
    clearAll,
    isMeasuring,
    measureType,
    hasError,
    errorMsg
  };
} 